package com.sicpa.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.sicpa.common.core.domain.AjaxResult;
import com.sicpa.common.core.domain.entity.AntiCounterfeitingRegisteredOffice;
import com.sicpa.common.core.domain.entity.SysRole;
import com.sicpa.common.core.domain.entity.SysUser;
import com.sicpa.common.core.page.TableDataInfo;
import com.sicpa.common.enums.ConfigKeyEnum;
import com.sicpa.common.enums.PerssionCheckEnum;
import com.sicpa.common.enums.ProcessOptResultsEnum;
import com.sicpa.common.enums.RoleEnum;
import com.sicpa.common.utils.SecurityUtils;
import com.sicpa.common.utils.StringUtils;
import com.sicpa.system.mapper.*;
import com.sicpa.system.service.IAntiCounterfeitingRegisteredOfficeService;
import com.sicpa.system.service.ICheckUserPowerService;
import com.sicpa.system.service.ISysConfigService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * AntiCounterfeitingRegisteredOfficeImpl
 *
 * @author lwf
 */
@Service
public class AntiCounterfeitingRegisteredOfficeServiceImpl implements IAntiCounterfeitingRegisteredOfficeService {

    private AntiCounterfeitingRegisteredOfficeMapper antiCounterfeitingRegisteredOfficeMapper;

    private SysUserMapper sysUserMapper;

    private ISysConfigService configService;

    private SysMenuMapper sysMenuMapper;

    private AntiCounterfeitingProcessRecordImpl antiCounterfeitingProcessRecordImpl;

    private ICheckUserPowerService iCheckUserPowerService;

    private SysRoleMapper sysRoleMapper;

    private SysUserRoleMapper sysUserRoleMapper;

    private SysRoleMenuMapper sysRoleMenuMapper;
    private AntiCounterfeitingProcessRecordMapper antiCounterfeitingProcessRecordMapper;


    private static final Logger log = LoggerFactory.getLogger(AntiCounterfeitingRegisteredOfficeServiceImpl.class);

    private static final Pattern CHINA_PATTERN = Pattern.compile("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$");

    @Autowired
    public AntiCounterfeitingRegisteredOfficeServiceImpl(AntiCounterfeitingRegisteredOfficeMapper antiCounterfeitingRegisteredOfficeMapper, SysUserMapper sysUserMapper, ISysConfigService configService, SysMenuMapper sysMenuMapper, AntiCounterfeitingProcessRecordImpl antiCounterfeitingProcessRecordImpl, ICheckUserPowerService iCheckUserPowerService, SysRoleMenuMapper sysRoleMenuMapper, SysRoleMapper sysRoleMapper, SysUserRoleMapper sysUserRoleMapper,AntiCounterfeitingProcessRecordMapper antiCounterfeitingProcessRecordMapper) {
        this.antiCounterfeitingRegisteredOfficeMapper = antiCounterfeitingRegisteredOfficeMapper;
        this.sysUserMapper = sysUserMapper;
        this.configService = configService;
        this.sysMenuMapper = sysMenuMapper;
        this.antiCounterfeitingProcessRecordImpl = antiCounterfeitingProcessRecordImpl;
        this.iCheckUserPowerService = iCheckUserPowerService;
        this.sysRoleMenuMapper = sysRoleMenuMapper;
        this.sysRoleMapper = sysRoleMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.antiCounterfeitingProcessRecordMapper = antiCounterfeitingProcessRecordMapper;
    }

//    /**
//     * 查询事务所列表
//     *
//     * @param office
//     * @return
//     */
//    @Override
//    public List<AntiCounterfeitingRegisteredOffice> selectOfficeList(AntiCounterfeitingRegisteredOffice office) {
//        //获取登录用户
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        //判断是普通事务所或者事务所管理员(是否是事务所账号，1：是，0：不是)
//        Integer isOfficeAccount = user.getIsOfficeAccount();
//        if (1 == isOfficeAccount) {
//            return antiCounterfeitingRegisteredOfficeMapper.selectByOfficeNumber(user.getUserName());
//        } else {
//            if (iCheckUserPowerService.noAdminHashRole(RoleEnum.OFFICE_GROUPING_ADMIN.getRoleKey())) {
//                List<String> list = antiCounterfeitingRegisteredOfficeMapper.selectOfficeIdList(user.getUserId());
//                return antiCounterfeitingRegisteredOfficeMapper.selectOfficeByOfficeId(list, office);
//            } else {
//                return antiCounterfeitingRegisteredOfficeMapper.selectOfficeList(office);
//            }
//        }
//    }

    /**
     * 上注协查询
     *
     * @param office
     * @return
     */
    @Override
    public List<AntiCounterfeitingRegisteredOffice> scipaSelect(AntiCounterfeitingRegisteredOffice office) {
        return antiCounterfeitingRegisteredOfficeMapper.selectOfficeList(office);
    }

    /**
     * 普通事务所查询
     *
     * @param office
     * @return
     */
    @Override
    public List<AntiCounterfeitingRegisteredOffice> puSelect(AntiCounterfeitingRegisteredOffice office) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        AntiCounterfeitingRegisteredOffice antiCounterfeitingRegisteredOffice = antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(user.getOfficeId());
        List<AntiCounterfeitingRegisteredOffice> list = new ArrayList<>();
        if (antiCounterfeitingRegisteredOffice != null) {
            list.add(antiCounterfeitingRegisteredOffice);
        }
        return list;
    }

    /**
     * 组长查询
     *
     * @param office
     * @param list
     * @return
     */
    @Override
    public List<AntiCounterfeitingRegisteredOffice> zuSelect(AntiCounterfeitingRegisteredOffice office, List<String> list) {
        List<AntiCounterfeitingRegisteredOffice> antiCounterfeitingRegisteredOffices = new ArrayList<>();
        if (Optional.ofNullable(list).isPresent() && list.size() > 0) {
            antiCounterfeitingRegisteredOffices = antiCounterfeitingRegisteredOfficeMapper.selectOfficeByOfficeId(list, office);
        }
        return antiCounterfeitingRegisteredOffices;
    }

    /**
     * 根据事务所id获取事务所
     *
     * @param officeId
     * @return
     */
    @Override
    public AntiCounterfeitingRegisteredOffice selectById(Long officeId) {
        return antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(officeId);
    }

    @Override
    public int isOfficeData(AntiCounterfeitingRegisteredOffice office) {
        int flag = -1;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        if (1 == isOfficeAccount) {
            Long officeId = user.getOfficeId();
            if (officeId.equals(office.getOfficeId())) {
                flag = 1;
            }
        } else {
            flag = 1;
        }
        return flag;
    }

    /**
     * 事务所编号 获取审核事务所详情
     *
     * @param officeId 事务所编号
     * @return
     */
    @Override
    public AntiCounterfeitingRegisteredOffice getDetailByNumber(Long officeId) {
        AntiCounterfeitingRegisteredOffice office =  antiCounterfeitingRegisteredOfficeMapper.getDetailByNumber(officeId);
        if(office.getAuditStatus() == 1 || office.getAuditStatus() == -2) {
            String optReason = antiCounterfeitingProcessRecordMapper.getReasonByItemIdAndItem(officeId, "anti_counterfeiting_registered_office", null);
            office.setOptReason(optReason);
            String username = antiCounterfeitingProcessRecordMapper.getUserByItemIdAndItem(officeId, "anti_counterfeiting_registered_office", null);
            office.setOptReason(optReason);
            office.setOptUser(username);
        }
        return office;
    }

    /**
     * 添加事务所
     *
     * @param office
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(AntiCounterfeitingRegisteredOffice office) {
        office.setFirmStatus("正常");
        antiCounterfeitingRegisteredOfficeMapper.insertSelective(office);
        Long reId =0L;
        if(office.getIsRegister() == 1){
             reId = addSystemUser(office, true);
        }else{
             reId = addSystemUser(office, false);
        }

        if (reId != null && !reId.equals(0L)) {
            office.setSystemAccountId(reId);
            antiCounterfeitingRegisteredOfficeMapper.updateOfficeByOfficeNum(office);
        }
        SysRole sysRole = sysRoleMapper.checkRoleKeyUnique(PerssionCheckEnum.OFFICE_BASIC_POWER.getPerssionKey());
        List<Long> menuIds = sysRoleMenuMapper.selectMenuIdsByRoleId(sysRole.getRoleId());
        antiCounterfeitingRegisteredOfficeMapper.batchOfficePowers(office.getOfficeId(), menuIds);
        return 1;
    }

    /**
     * 修改事务所
     *
     * @param office
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(AntiCounterfeitingRegisteredOffice office) {
        String practiceCertificateNo = office.getPracticeCertificateNo();
        Long officeId = office.getOfficeId();
        String phoneNumberOfContactPerson = office.getPhoneNumberOfContactPerson();
        AntiCounterfeitingRegisteredOffice query = new AntiCounterfeitingRegisteredOffice();
        query.setPhoneNumberOfContactPerson(phoneNumberOfContactPerson);
        List<AntiCounterfeitingRegisteredOffice> officeList = antiCounterfeitingRegisteredOfficeMapper.selectOfficeList(query);
        //不可以改
        if (sysUserMapper.checkOfficeUserNameUnique(office.getFirmName()) > 0 && (!practiceCertificateNo.equals(antiCounterfeitingRegisteredOfficeMapper.selectPracticeCertificateNoByFriName(office.getFirmName())))) {
            return AjaxResult.error("修改事务所'" + office.getFirmName() + "'失败，事务所名称已存在");
        } else if (officeList.size() > 0 && !officeId.equals(officeList.get(0).getOfficeId())) {
            return AjaxResult.error("修改事务所'" + office.getFirmName() + "'失败，联系人手机号码已存在");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        if (isOfficeAccount == 1) {
            Long reId = addSystemUser(office, false);
            if (!reId.equals(0L)) {
                office.setSystemAccountId(reId);
            }
        } else if (isOfficeAccount == 0) {
            List<SysUser> list = office.getOfficeUserList();
            for(int i=0;i<list.size();i++){
                SysUser item = list.get(i);
                sysUserMapper.updateContractUser(item);
            }
        }
        antiCounterfeitingRegisteredOfficeMapper.updateByPrimaryKeySelective(office);
        return AjaxResult.success();
    }

    /**
     * 添加事务所普通用户
     *
     * @param sysUser
     * @return
     */
    @Override
    public int addOfficeUser(SysUser sysUser) {
        String userName = sysUser.getUserName();
        if (StringUtils.isNotEmpty(userName)) {
            int userNameUnique = sysUserMapper.checkUserNameUnique(userName);
            if (userNameUnique > 0) {
                return -1;
            } else {
                // 新增
                sysUser.setIsOfficeAdmin(0);
                sysUser.setIsOfficeAccount(1);

                String password = configService.selectConfigByKey(ConfigKeyEnum.SYS_USER_INITPASSWORD.getValue());
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                sysUserMapper.insertUser(sysUser);
            }
        }
        return 0;
    }

    /**
     * 查询该事务所最大序号
     *
     * @param office
     * @return
     */
    @Override
    public Map<String, Object> selectMaxSortOffice(AntiCounterfeitingRegisteredOffice office) {
        Map<String, Object> map = new HashMap<>();
        int sortMax = sysUserMapper.selectMaxSortOffice(office.getOfficeId()) + 1;
        String practiceCertificateNo = office.getPracticeCertificateNo();
        if (sortMax < 10) {
            map.put("userName", practiceCertificateNo + "00" + sortMax);
        } else {
            map.put("userName", practiceCertificateNo + "0" + sortMax);
        }
        map.put("sortNum", sortMax);
        return map;
    }

    /**
     * 添加事务所初始用户，不存在添加，存在更新
     *
     * @param office
     * @param isRegister
     * @return
     */
    private Long addSystemUser(AntiCounterfeitingRegisteredOffice office, Boolean isRegister) {
        String practiceCertificateNo = office.getPracticeCertificateNo();
        SysUser sysUser = new SysUser();
        if (StringUtils.isNotEmpty(practiceCertificateNo)) {

            sysUser.setOfficeId(office.getOfficeId());
            sysUser.setIsOfficeAdmin(1);
            sysUser.setSortNum(1);
            sysUser.setTelephone(office.getOperatorNumber());
            sysUser.setPhonenumber(office.getPhoneNumberOfOperator());
            sysUser.setUserName(practiceCertificateNo);
            sysUser.setNickName(office.getOperator());
            sysUser.setIsOfficeAccount(1);
            if(isRegister){
                sysUser.setStatus("1");
            }else{
                sysUser.setStatus("0");
            }

            int userNameUnique = sysUserMapper.checkUserNameUnique(practiceCertificateNo);
            if (userNameUnique > 0) {
                // 修改
                Long userId = sysUserMapper.selectIdByUserName(practiceCertificateNo);
                sysUser.setUserId(userId);
                sysUser.setIsResetPwd(null);
                sysUserMapper.updateUser(sysUser);
            } else {
                // 新增

                String password = configService.selectConfigByKey(ConfigKeyEnum.SYS_USER_INITPASSWORD.getValue());
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                sysUserMapper.insertUser(sysUser);
            }
        }
        return sysUser.getUserId();
    }

    /**
     * 导入事务所
     *
     * @param officeList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importOffice(List<AntiCounterfeitingRegisteredOffice> officeList) {
        Map<String, Object> result = new HashMap<>();
        Integer add = 0;
        StringBuilder failureItem = new StringBuilder();
        Integer update = 0;
        Integer fail = 0;
        Long reId;
        //数据错误的行记录 记录具体错误信息
        List<String> failureItemList = new ArrayList<>();
        if (officeList != null && officeList.size() > 0) {
            for (int i = 0; i < officeList.size(); i++) {
                Boolean flag = true;
                AntiCounterfeitingRegisteredOffice office = officeList.get(i);
                String officeNumber = office.getOfficeNumber();
                String branchOfficeSign = office.getBranchOfficeSign();
                //事务所名称
                String firmName = office.getFirmName();
                String firmNameBranch = office.getFirmNameBranch();
                //事务所执业证书编号
                String practiceCertificateNo = office.getPracticeCertificateNo();
                String practiceCertificateNoFs = office.getPracticeCertificateNoFs();
                String unifiedSocialCreditCode = office.getUnifiedSocialCreditCode();
                //是否有证券资格
                String haveSecuritiesQualification = office.getHaveSecuritiesQualification();
                StringBuffer falseInfo = new StringBuffer();
                falseInfo.append("Excel第" + (i + 2) + "行错误：");
                /*if(StringUtils.isEmpty(haveSecuritiesQualification)){
                    falseInfo.append("是否有证券资格为必填项 ");
                    flag = false;
                }else {*/
                if (StringUtils.isNotEmpty(haveSecuritiesQualification)) {
                    if (!(haveSecuritiesQualification.trim().equals("是") || haveSecuritiesQualification.trim().equals("否"))) {
                        falseInfo.append("是否有证券资格填写错误 ");
                        flag = false;
                    }
                }
                // }
                //是否有H股资格
                String haveHShareQualification = office.getHaveHShareQualification();
                if (StringUtils.isNotEmpty(haveHShareQualification)) {
                    if (!(haveHShareQualification.equals("是") || haveHShareQualification.equals("否"))) {
                        falseInfo.append("是否有H股资格填写错误 ");
                        flag = false;
                    }
                }
                //所属省份
                String province = office.getProvince();
                if (StringUtils.isEmpty(province)) {
                    falseInfo.append("所属省份为必填项 ");
                    flag = false;
                }

                //通讯地址
                String mailingAddress = office.getMailingAddress();
                if (StringUtils.isEmpty(mailingAddress)) {
                    falseInfo.append("通讯地址为必填项 ");
                    flag = false;
                }

                //批准执业文号
                String licenseNo = office.getLicenseNo();
                if (StringUtils.isEmpty(licenseNo)) {
                    falseInfo.append("批准执业文号为必填项 ");
                    flag = false;
                }
                //批准执业日期
                String approvedPracticeDate = office.getApprovedPracticeDate();
                if (StringUtils.isEmpty(approvedPracticeDate)) {
                    falseInfo.append("批准执业日期为必填项 ");
                    flag = false;
                }
                //注册会计师数量
                String numberOfCpas = office.getNumberOfCpas();
                if (StringUtils.isEmpty(numberOfCpas)) {
                    falseInfo.append("注册会计师数量为必填项 ");
                    flag = false;
                } else {
                    Pattern pattern = Pattern.compile("[0-9]*");
                    Matcher isNum = pattern.matcher(numberOfCpas);
                    boolean matches = isNum.matches();
                    if (!matches) {
                        falseInfo.append("注册会计师数量为数字 ");
                        flag = false;
                    }
                }
                //股东合伙人数
                String numberOfPartners = office.getNumberOfPartners();
                if (StringUtils.isNotEmpty(numberOfPartners)) {
                    Pattern pattern = Pattern.compile("[0-9]*");
                    Matcher isNum = pattern.matcher(numberOfPartners);
                    boolean matches = isNum.matches();
                    if (!matches) {
                        falseInfo.append("股东合伙人数为数字 ");
                        flag = false;
                    }
                }
                //其中分所注师数量
                String numberOfBranchRegisteredEngineers = office.getNumberOfBranchRegisteredEngineers();
                if (StringUtils.isNotEmpty(numberOfBranchRegisteredEngineers)) {
                    Pattern pattern = Pattern.compile("[0-9]*");
                    Matcher isNum = pattern.matcher(numberOfBranchRegisteredEngineers);
                    boolean matches = isNum.matches();
                    if (!matches) {
                        falseInfo.append("其中分所注师数量为数字 ");
                        flag = false;
                    }
                }
                //注册资本(万元)
                String registeredCapital = office.getRegisteredCapital();
                if (StringUtils.isNotEmpty(registeredCapital)) {
                    Pattern pattern = Pattern.compile("^(([0-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))$");
                    Matcher isNum = pattern.matcher(registeredCapital);
                    boolean matches = isNum.matches();
                    if (!matches) {
                        falseInfo.append("请填写正确的注册资本(万元) ");
                        flag = false;
                    }
                }
                //邮政编码
                String postalCode = office.getPostalCode();
                if (StringUtils.isEmpty(postalCode)) {
                    falseInfo.append("邮政编码为必填项 ");
                    flag = false;
                }
                //联系人
                String contacts = office.getContacts();
                if (StringUtils.isEmpty(contacts)) {
                    falseInfo.append("联系人为必填项 ");
                    flag = false;
                }
                //联系电话
                String contactNumber = office.getContactNumber();
                if (StringUtils.isEmpty(contactNumber)) {
                    falseInfo.append("联系电话(财政系统)为必填项 ");
                    flag = false;
                }
                //联系人手机号
                String phoneNumberOfContactPerson = office.getPhoneNumberOfContactPerson();
                if (StringUtils.isNotEmpty(phoneNumberOfContactPerson)) {
                    Matcher m = CHINA_PATTERN.matcher(phoneNumberOfContactPerson);
                    if (!m.matches()) {
                        falseInfo.append("请填写正确的联系人手机号 ");
                        flag = false;
                    }
                }
                //20201214，根据要求：操作人、操作人联系电话、操作人手机号改为不必填
                //操作人
                /*String operator = office.getOperator();
                if(StringUtils.isEmpty(operator.trim())){
                    falseInfo.append("操作人为必填项 ");
                    flag = false;
                }*/
                //联系电话
                /*String operatorNumber = office.getOperatorNumber();
                if(StringUtils.isEmpty(operatorNumber)){
                    falseInfo.append("联系电话(操作人)为必填项 ");
                    flag = false;
                }*/

                //操作人手机号
                String phoneNumberOfOperator = office.getPhoneNumberOfOperator();
                /*if(StringUtils.isEmpty(phoneNumberOfOperator.trim())){
                    falseInfo.append("操作人手机号为必填项 ");
                    flag = false;
                }else{*/
                if (StringUtils.isNotEmpty(phoneNumberOfOperator)) {
                    Matcher m = CHINA_PATTERN.matcher(phoneNumberOfOperator);
                    if (!m.matches()) {
                        falseInfo.append("请填写正确的操作人手机号 ");
                        flag = false;
                    }
                }
                /*}*/

                //经营场所
                String placeOfBusiness = office.getPlaceOfBusiness();
                if (StringUtils.isEmpty(placeOfBusiness)) {
                    falseInfo.append("经营场所为必填项 ");
                    flag = false;
                }
                if (StringUtils.isEmpty(practiceCertificateNo) && StringUtils.isEmpty(practiceCertificateNoFs)) {
                    falseInfo.append("事务所执业证书编号为必填项 ");
                    flag = false;
                }
                if (StringUtils.isEmpty(firmName) && StringUtils.isEmpty(firmNameBranch)) {
                    falseInfo.append("事务所名称为必填项 ");
                    flag = false;
                }
                if (StringUtils.isEmpty(unifiedSocialCreditCode)) {
                    falseInfo.append("统一社会信用代码为必填项 ");
                    flag = false;
                }
                if (StringUtils.isEmpty(officeNumber)) {
                    office.setOfficeNumber(branchOfficeSign);
                }
                if (StringUtils.isNotEmpty(practiceCertificateNoFs) && StringUtils.isNotEmpty(firmNameBranch)) {
                    office.setHeadOfficeOrBranchOffice("2");
                    office.setPracticeCertificateNo(practiceCertificateNoFs);
                    office.setFirmName(firmNameBranch);
                }
                //事务所状态
                String firmStatus = office.getFirmStatus();
                if (!Optional.ofNullable(firmStatus).isPresent()) {
                    office.setFirmStatus("正常");
                }
                if (!flag) {
                    fail++;
                    String failInfo = falseInfo.toString().trim();
                    failureItemList.add(failInfo);
                    continue;
                }
                try {
                    //通过证书编号 查询是否有正常使用的事务所
                    Integer tem = antiCounterfeitingRegisteredOfficeMapper.selectCountByPracticeCertificateNo(office.getPracticeCertificateNo());
                    if (tem != null && tem > 0) {
                        List<AntiCounterfeitingRegisteredOffice> officeList1 = antiCounterfeitingRegisteredOfficeMapper.selectByPracticeCertificateNo(office.getPracticeCertificateNo());
                        if (officeList1.size() == 1) {
                            office.setOfficeId(officeList1.get(0).getOfficeId());
                        } else {
                            fail++;
                            failureItemList.add("Excel第" + (i + 2 + "行事务所证书号不匹配"));
                            continue;
                        }
                        //更新
                        int ancount = antiCounterfeitingRegisteredOfficeMapper.updateOfficeByOfficeNum(office);
                        if (ancount > 0) {
                            update++;
                        }
                    } else {
                        //事务所名称 firmName
                        int count = antiCounterfeitingRegisteredOfficeMapper.selectByFirmNameOrOfficeNumber(office.getFirmName());
                        if (count > 0) {
                            fail++;
                            failureItemList.add("Excel第" + (i + 2 + "行事务所名或事务所名称（分所）称重复"));
                            continue;
                        }
                        //新增
                        antiCounterfeitingRegisteredOfficeMapper.insertSelective(office);
                        // 导入
                        SysRole sysRole = sysRoleMapper.checkRoleKeyUnique(PerssionCheckEnum.OFFICE_BASIC_POWER.getPerssionKey());
                        List<Long> menuIds = sysRoleMenuMapper.selectMenuIdsByRoleId(sysRole.getRoleId());
                        antiCounterfeitingRegisteredOfficeMapper.batchOfficePowers(office.getOfficeId(), menuIds);
                        add++;
                    }
                    reId = addSystemUser(office, false);
                    if (reId != null && !reId.equals(0L)) {
                        office.setSystemAccountId(reId);
                        antiCounterfeitingRegisteredOfficeMapper.updateOfficeByOfficeNum(office);
                    }
                } catch (Exception e) {
                    fail++;
                    log.error(e.getMessage(), e);
                    failureItemList.add(("Excel第" + (i + 2) + "行未知错误"));
                }
            }
        }
        result.put("add", add);
        result.put("failureItemList", failureItemList);
        result.put("update", update);
        result.put("fail", fail);
        return result;
    }

    /**
     * 根据事务所id重置事务所账号密码
     *
     * @param officeId
     * @return
     */
    @Override
    public int resetPwdByOfficeId(Long officeId) {
        AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectByPrimaryKey(officeId);
        String password = configService.selectConfigByKey(ConfigKeyEnum.SYS_USER_INITPASSWORD.getValue());
        String encPwd = SecurityUtils.encryptPassword(password);
        SysUser user = sysUserMapper.selectUserByUserName(office.getPracticeCertificateNo());
        user.setPassword(encPwd);
        user.setIsResetPwd(1);
        return sysUserMapper.updateUser(user);
    }

//    /**
//     * 权限列表页面查询事务所
//     *
//     * @param office
//     * @return
//     */
//    @Override
//    public List<Map<String, Object>> selectNumberName(AntiCounterfeitingRegisteredOffice office) {
//        //获取登录用户
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        //判断是普通事务所或者事务所管理员(是否是事务所账号，1：是，0：不是)
//        Integer isOfficeAccount = user.getIsOfficeAccount();
//        if (1 == isOfficeAccount) {
//            return antiCounterfeitingRegisteredOfficeMapper.selectNumberNamebyOfficeNumber(user.getUserName(), office);
//        } else {
//            if (iCheckUserPowerService.noAdminHashRole(RoleEnum.OFFICE_GROUPING_ADMIN.getRoleKey())) {
//                List<String> list = antiCounterfeitingRegisteredOfficeMapper.selectOfficeIdList(user.getUserId());
//                return antiCounterfeitingRegisteredOfficeMapper.selectNumberNameByOfficeId(list, office);
//            } else {
//                return antiCounterfeitingRegisteredOfficeMapper.selectNumberName(office);
//            }
//        }
//    }

    /**
     * 查询事务所组长管理的事务所id
     *
     * @return
     */
    @Override
    public List<String> selectOfficeIdList() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return antiCounterfeitingRegisteredOfficeMapper.selectOfficeIdList(user.getUserId());
    }

    /**
     * 普通事务所查询
     *
     * @param office
     * @return
     */
    @Override
    public List<Map<String, Object>> officeSelect(AntiCounterfeitingRegisteredOffice office) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return antiCounterfeitingRegisteredOfficeMapper.selectNumberNamebyOfficeNumber(user.getUserName(), office);
    }

    /**
     * 事务所组长查询
     *
     * @param office
     * @param list
     * @return
     */
    @Override
    public List<Map<String, Object>> officeAdminSelect(AntiCounterfeitingRegisteredOffice office, List<String> list) {
        return antiCounterfeitingRegisteredOfficeMapper.selectNumberNameByOfficeId(list, office);
    }

    /**
     * 上注协查询
     *
     * @param office
     * @return
     */
    @Override
    public List<Map<String, Object>> adminSelect(AntiCounterfeitingRegisteredOffice office) {
        return antiCounterfeitingRegisteredOfficeMapper.selectNumberName(office);
    }

    /**
     * 事务所列表页面权限数据处理
     *
     * @param tableDataInfo
     * @param list
     * @return
     */
    @Override
    public TableDataInfo officePowerDataHander(TableDataInfo tableDataInfo, List<Map<String, Object>> list) {
        List<Map<String, Object>> menuList = sysMenuMapper.selectMenuidAndName();
        List<Map<String, Object>> resultD = new ArrayList<>();
        if (list != null && list.size() > 0 && menuList != null && menuList.size() > 0) {
            for (Map<String, Object> temp : list) {
                Long officeId = (Long) temp.get("office_id");
                for (Map<String, Object> menuT : menuList) {
                    Long menuId = (Long) menuT.get("value");
                    Long result = antiCounterfeitingRegisteredOfficeMapper.selectJurisdiction(officeId, menuId);
                    temp.put(menuId.toString(), result);
                }
                resultD.add(temp);
            }
        }
        Map<String, Object> temMap = new HashMap<>(3);
        temMap.put("name", "事务所执业证书编号");
        temMap.put("value", "practice_certificate_no");
        Map<String, Object> clone = (Map<String, Object>) ((HashMap<String, Object>) temMap).clone();
        menuList.add(0, clone);
        temMap.clear();
        temMap.put("name", "事务所名称");
        temMap.put("value", "firm_name");
        menuList.add(1, temMap);
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("head", menuList);
        map.put("data", resultD);
        resultList.add(map);
        tableDataInfo.setRows(resultList);
        return tableDataInfo;
    }

    /**
     * 根据事务所id加载事务所权限树
     *
     * @param officeId
     * @return
     */
    @Override
    public Map<String, Object> getOfficePowersByOfficeId(Long officeId) {
        List<Map<String, Object>> sysMenus = sysMenuMapper.selectTopOfficeMenu(0L);
        List<Map<String, Object>> menuResult = new ArrayList<>();
        if (sysMenus != null && sysMenus.size() > 0) {
            for (Map<String, Object> sysMenu : sysMenus) {
                Long id = (Long) sysMenu.get("id");
                List<Map<String, Object>> childMenu = sysMenuMapper.selectTopOfficeMenu(id);
                if (childMenu != null && childMenu.size() > 0) {
                    List<Map<String, Object>> tChild = new ArrayList<>();
                    for (Map<String, Object> fMenu : childMenu) {
                        Long tId = (Long) fMenu.get("id");
                        List<Map<String, Object>> tmenu = sysMenuMapper.selectTopOfficeMenu(tId);
                        if (tmenu != null && tmenu.size() > 0) {
                            List<Map<String, Object>> omenus = new ArrayList<>();
                            for (Map<String, Object> oMenu : tmenu) {
                                Long oId = (Long) oMenu.get("id");
                                List<Map<String, Object>> omenuT = sysMenuMapper.selectTopOfficeMenu(oId);
                                if (omenuT != null && omenuT.size() > 0) {
                                    oMenu.put("children", omenuT);
                                }
                                omenus.add(oMenu);
                            }
                            fMenu.put("children", omenus);
                        }
                        tChild.add(fMenu);
                    }
                    sysMenu.put("children", tChild);
                }
                menuResult.add(sysMenu);
            }
        }
        List<Long> checked = sysMenuMapper.selectMenuIdsByOfficeId(officeId);
        Map<String, Object> endResult = new HashMap<>();
        endResult.put("checked", checked);
        endResult.put("menus", menuResult);
        return endResult;
    }

    /**
     * 批量新增事务所权限
     *
     * @param officeId
     * @param powerIds
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOfficePowers(Long officeId, List<Long> powerIds) {
        antiCounterfeitingRegisteredOfficeMapper.deletePowersByOfficeId(officeId);
        if (StringUtils.isNotEmpty(powerIds)) {
            antiCounterfeitingRegisteredOfficeMapper.batchOfficePowers(officeId, powerIds);
        }
    }

    /**
     * 根据事务所ID 获取审核事务所详情
     *
     * @param officeId 事务所id
     * @return
     */
    @Override
    public AntiCounterfeitingRegisteredOffice getDetailById(Long officeId) {
        return antiCounterfeitingRegisteredOfficeMapper.getDetailById(officeId);
    }

    /**
     * 修改账号有效期
     *
     * @param office
     * @return
     */
    @Override
    public int editValidity(AntiCounterfeitingRegisteredOffice office) {
        return antiCounterfeitingRegisteredOfficeMapper.updateByPrimaryKeySelective(office);
    }

    /**
     * 批量删除事务所,状态为3, 未启用的可以删除,其他的不能删除
     *
     * @param officeIds
     * @return
     */
    @Override
    public int deleteOffices(Long[] officeIds) {
        return antiCounterfeitingRegisteredOfficeMapper.deleteOffices(officeIds);
    }

    /**
     * 1：恢复，2：终止
     *
     * @param officeId 事务所id
     * @param status   状态id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStatus(Long officeId, int status) {
        //修改事务所状态
        int result = antiCounterfeitingRegisteredOfficeMapper.updateStatus(officeId, status);
        //根据事务所编号同步修改用户信息表
        AntiCounterfeitingRegisteredOffice antiCounterfeitingRegisteredOffice = antiCounterfeitingRegisteredOfficeMapper.selectByPrimaryKey(officeId);
        String practiceCertificateNo = antiCounterfeitingRegisteredOffice.getPracticeCertificateNo();
        SysUser sysUser = sysUserMapper.selectUserByUserName(practiceCertificateNo);
        Long userId = sysUser.getUserId();
        Integer isRegister = antiCounterfeitingRegisteredOffice.getIsRegister();
        if (1 == status) {
            antiCounterfeitingRegisteredOfficeMapper.updateFirmStatusByOfficeId(officeId, "正常");
            if (isRegister == 1) {
                // 外省注册恢复事务所临时权限
                sysUserRoleMapper.deleteUserRoleByUserId(userId);
                SysRole sysRole = sysRoleMapper.checkRoleKeyUnique(PerssionCheckEnum.OFFICE_TEMP.getPerssionKey());
                sysUserRoleMapper.insertUserRole(userId, sysRole.getRoleId());
            } else {
                SysRole sysRole = sysRoleMapper.checkRoleKeyUnique(PerssionCheckEnum.OFFICE_BASIC_POWER.getPerssionKey());
                List<Long> menuIds = sysRoleMenuMapper.selectMenuIdsByRoleId(sysRole.getRoleId());
                saveOfficePowers(officeId, menuIds);
            }
            //用户正常
            sysUserMapper.updateStatus(practiceCertificateNo, 0);
        } else if (2 == status) {
            antiCounterfeitingRegisteredOfficeMapper.updateFirmStatusByOfficeId(officeId, "暂停");
            SysRole sysRole = sysRoleMapper.checkRoleKeyUnique(RoleEnum.OFFICE_LIMIT_VIEW.getRoleKey());
            // 限制用户权限只能查看
            if (isRegister == 1) {
                sysUserRoleMapper.deleteUserRoleByUserId(userId);
                sysUserRoleMapper.insertUserRole(userId, sysRole.getRoleId());
            } else {
                List<Long> menuIds = sysRoleMenuMapper.selectMenuIdsByRoleId(sysRole.getRoleId());
                saveOfficePowers(officeId, menuIds);
            }
        } else if (3 == status) {
            antiCounterfeitingRegisteredOfficeMapper.updateFirmStatusByOfficeId(officeId, "停用");
            //用户停用
            sysUserMapper.updateStatus(practiceCertificateNo, 1);
        }
        return result;
    }

    /**
     * 审核事务所
     *
     * @param office 事务所实体
     * @return
     * @author wph 20200909
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult audit(AntiCounterfeitingRegisteredOffice office) {
        int result = 0;
        //审核未通过,调用方法在审核表添加相关数据
        Long officeId = office.getOfficeId();
        if (!Optional.ofNullable(officeId).isPresent()) {
            return AjaxResult.error("数据为空,请重试");
        }
        if (office.getAuditStatus() == -2) {
            //只判断操作项id不为空,审核不通过原因必填
            result = antiCounterfeitingProcessRecordImpl.add(officeId, "anti_counterfeiting_registered_office", ProcessOptResultsEnum.FAILED_TO_PASS_AUDIT.getName(), office.getOptReason(), SecurityUtils.getUsername());
            //更新数据库审核状态
            antiCounterfeitingRegisteredOfficeMapper.updateAduitStatusByOfficeId(officeId, -1, "停用", -2, null);
            //antiCounterfeitingRegisteredOfficeMapper.deletePowersByOfficeId(officeId);
            sysUserMapper.updateUserDelFlag(officeId);
        }
        //审核通过
        else if (office.getAuditStatus() == 1) {
            //判断操作项id和审核通过原因不为空
            result = antiCounterfeitingProcessRecordImpl.add(officeId, "anti_counterfeiting_registered_office", ProcessOptResultsEnum.APPROVED.getName(), office.getOptReason(), SecurityUtils.getUsername());
            tempAudit(office);
        }
        return AjaxResult.success(result);
    }

    /**
     * 更改数据库审核状态添加用户通用方法
     *
     * @param office
     * @return
     */
    private void tempAudit(AntiCounterfeitingRegisteredOffice office) {
        //更新数据库审核状态
        antiCounterfeitingRegisteredOfficeMapper.updateAduitStatusByOfficeId(office.getOfficeId(), 1, "正常", 1, office.getEffectTime());
        //查询officeNumber ,为增加新用户做准备
        office = antiCounterfeitingRegisteredOfficeMapper.selectByPrimaryKey(office.getOfficeId());
        //审核通过,添加用户
        addSystemUser(office, false);
    }

    @Override
    public List<Map<String, Object>> selectListAudit(String firmName, String practiceCertificateNo, Integer auditStatus) {
        return antiCounterfeitingRegisteredOfficeMapper.selectListAudit(firmName, practiceCertificateNo, auditStatus);
    }

    @Override
    public int updateAudit(AntiCounterfeitingRegisteredOffice office) {
        //默认修改完后审核状态改为待审核0
        return antiCounterfeitingRegisteredOfficeMapper.updateAudit(office);
    }
}
